package com.cloudsubassemblykafka10024.quickstart;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @Description: Kafka 消费者入门
 * @Author zx
 * @Date 2024/12/24 20:00
 * @Version 1.0
 */
public class KafkaConsumerQuickStart_002 {
    public static void main(String[] args) {

        // 创建 Kafka Consumer
        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.18.220:9092");
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "group1");

        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(properties);

        // 手动指定消费分区
        List<TopicPartition> topicPartitionList = Arrays.asList(new TopicPartition("messageDML001", 0));
        // 订阅主题 , 手动指定消费分区 这种指定将失去组管理特性
        kafkaConsumer.assign(topicPartitionList);


        // 设置消费分区指定的位置 从头开始消费
        kafkaConsumer.seekToBeginning(topicPartitionList);
        // 设置消费分区指定的位置 从尾开始消费
        // kafkaConsumer.seekToEnd(topicPartitionList);
        // 设置消费分区指定的位置 从指定位置开始消费
        // kafkaConsumer.seek(topicPartitionList.get(0), 5);
        // 遍历消息队列
        while (true) {
            ConsumerRecords<String, String> consumerRecords = kafkaConsumer.poll(Duration.ofSeconds(30));
            if (!consumerRecords.isEmpty()) {
                Iterator<ConsumerRecord<String, String>> iterator = consumerRecords.iterator();
                while (iterator.hasNext()) {
                    // 获取消息
                    ConsumerRecord<String, String> record = iterator.next();
                    System.out.println("消息已消费");
                    System.out.println(record.topic() + ":" + record.partition() + ":" + record.offset() + ":" + record.key() + ":" + record.value() + ":" + record.timestamp());
                }
            }
        }
    }
}
